Crate axum_serde

source ·
Expand description

axum-serde

crates.io crates.io download LICENSE dependency status GitHub Workflow Status Coverage Status

📑 Overview

axum-serde is a library that provides multiple serde-based extractors / responses for the Axum web framework. It also offers a macro to easily customize extractors and responses without writing much boilerplate code.

If you were using crates like axum-yaml, axum-msgpack etc. in axum 0.6 and wish to upgrade to axum 0.7, axum-serde can be used as a replacement to simplify the migration, without having to modify existing code too much.

🚀 Basic usage

  • Install
cargo add axum-serde --features yaml
# Enable features as you need
  • Example
use axum::routing::{get, post};
use axum::Router;
use axum_serde::Yaml;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use tokio::net::TcpListener;

#[derive(Deserialize, Serialize)]
pub struct Data {
    pub v0: usize,
    pub v1: usize,
}

pub async fn extractor(Yaml(_data): Yaml<Data>) {
    // use _data
}

pub async fn response() -> Yaml<Data> {
    todo!()
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let router = Router::new()
        .route("/data", post(extractor))
        .route("/data", get(response));
    let listener = TcpListener::bind(&SocketAddr::from(([0u8, 0, 0, 0], 0u16))).await?;
    axum::serve(listener, router.into_make_service()).await?;
    Ok(())
}

🗂️ Extractors / responses

ExtractorFeatureBackend
Yaml<T>yamlserde_yaml v0.9.27
MsgPack<T> / MsgPackRaw<T>msgpackrmp-serde v1.1.2
Toml<T>tomltoml v0.8.8
Xml<T>xmlquick-xml v0.31.0

🎁 Custom extractor / response

Use the extractor macro to create custom extractors with minimal boilerplate:

  • Example
use axum_serde::{
    extractor,
    macros::{DeserializeOwned, Serialize},
};

extractor!(
    MyFormat,                   // The name of the data format.
    MyFmt,                      // The actual type name of the HTTP extractor/response.
    "application/myfmt",        // The Content-Type that this extractor supports.
    from_slice,                 // A function identifier for deserializing data from the HTTP request body.
    String,                     // The type of error that can occur when deserializing from the request body.
    to_vec,                     // A function identifier for serializing the HTTP response body to bytes.
    myfmt                       // The test module name.
);

fn from_slice<T: DeserializeOwned>(_bytes: &[u8]) -> Result<T, String> {
    todo!()
}

fn to_vec<T: Serialize>(_value: &T) -> Result<Vec<u8>, String> {
    todo!()
}
  • Test

More dev-dependencies are required to run the tests:

# Add dev-dependencies for tests
cargo add axum-test --dev
cargo add serde --features derive --dev
cargo add tokio --features macros --dev

# Run the generated tests
cargo test myfmt

📜 License

This project is licensed under the MIT License.

📚 References

Re-exports

Modules

Macros

  • This macro is designed to create an extractor type. It uses serde for extracting data from requests and serializing data into response body.

Functions

  • Checks if the content type in the given headers matches the expected content type.